﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumProject.Models;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.Data;
using ScrumProject.ViewModels;
using System.Web.Routing;

namespace ScrumProject.Controllers
{
    public class LoginController : Controller
    {
        private UserRepository userR = new UserRepository();
        private SMRPO6Context db = new SMRPO6Context();
        //
        // GET: /login/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /login/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Username, model.Password))
                {
                    User user = userR.GetByUsername(model.Username);
                    string roles = null;
                    // Build a roles string if we recognize the user
                    if (user.isAdmin)
                    {
                        roles = "admin";
                    }
                    else
                    {
                        roles = "user";
                    }
                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.UserId = user.Id;
                    serializeModel.Username = user.Username;
                    serializeModel.Roles = new String[1]{roles};

                    JavaScriptSerializer serializer = new JavaScriptSerializer();

                    string userData = serializer.Serialize(serializeModel);

                    FormsAuthenticationTicket authTicket =
                    new FormsAuthenticationTicket(1,
                                                        user.Username,
                                                        DateTime.Now,
                                                        DateTime.Now.AddMinutes(45),
                                                        model.RememberMe,
                                                        userData);
                    string encTicket = FormsAuthentication.Encrypt(authTicket);

                    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(faCookie);

                    //FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /login/LogOff
        [Authorize]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            HttpCookie c = Request.Cookies["MyCookie"];
            if (c != null)
            {
                c = new HttpCookie("MyCookie");
                c["AT"] = null;
                c.Expires = DateTime.Now.AddDays(-1);
                Request.Cookies.Add(c);
            }

            return RedirectToAction("Index", "Home");
        }

        [Authorize]
        public ActionResult MyProfile()
        {
            User userDetail = null;
            try
            {
                userDetail = userR.GetUser(((CustomPrincipal)User).UserId);
            }
            catch (Exception)
            {
                return RedirectToAction("LogOff");
            }

            return View(userDetail);
        }

        //
        // POST
        [Authorize]
        [HttpPost]
        public ActionResult MyProfile(User user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (userR.GetUsername(user.Id) == user.Username)
                    {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        return View();
                    }
                    else if (userR.GetByUsername(user.Username) == null)
                    {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        return View();
                    }
                    else
                    {
                        ModelState.AddModelError("", "The username is already used.");
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View();
        }

        [Authorize]
        public ActionResult Password()
        {
            ResetPasswordViewModel userDetail = new ResetPasswordViewModel();
            /*try
            {
                userR.GetUser(((CustomPrincipal)User).UserId);
            }
            catch (DataException)
            {
                return RedirectToAction("LogOff");
            }*/

            return View(userDetail);
        }

        //
        // POST
        [Authorize]
        [HttpPost]
        public ActionResult Password(ResetPasswordViewModel password)
        {
            try
            {
                User user = userR.GetUser(((CustomPrincipal)User).UserId);
                //UpdateModel(user);
                if (user.Password == password.ConfirmPassword)
                    return RedirectToAction("Index", "Home");
                if (password.ConfirmPassword == password.NewPassword)
                {
                    user.Password = password.NewPassword;
                    if (user.Email == null)
                        user.Email = "";
                    userR.UpdateUserPassword(user);
                    return RedirectToAction("Password");
                    
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View();
        }

    }
}
